package com.jeeplus.modules.sys.utils;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeeplus.modules.sys.entity.*;
import sun.nio.cs.ext.MacArabic;

import com.google.gson.Gson;
import com.jeeplus.common.utils.HttpUtils;
import com.jeeplus.common.utils.SpringContextHolder;

public class WeChatTokenUtil {
	/**
	 * 微信后台请求token工具类
	 */
	// 获取access_token的接口地址（GET）
	public final static String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=CorpID&corpsecret=SECRET";
	public final static String create_user_url = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=ACCESS_TOKEN";
	public final static String delete_user_url = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=ACCESS_TOKEN&userid=USERID";
	private static Gson gson;
	private static AccessToken accessToken;
	private static UserInfo userInfo;
	private static TextMsg textMsg;
	private static Mpnews mpnews;
	/**
	 * 获取access_token
	 * 
	 * CorpID
	 *            企业Id
	 * SECRET
	 *            管理组的凭证密钥，每个secret代表了对应用、通讯录、接口的不同权限；不同的管理组拥有不同的secret
	 * @return
	 */
	public static AccessToken getAddressBookAccessToken() {
		return getAccessToken(ParamesAPI.addressBookSecret);
	}

	/**
	 * 获取access_token
	 *
	 * CorpID
	 *            企业Id
	 * SECRET
	 *            管理组的凭证密钥，每个secret代表了对应用、通讯录、接口的不同权限；不同的管理组拥有不同的secret
	 * @return
	 */
	public static AccessToken getBiddingAccessToken() {
		return getAccessToken(ParamesAPI.biddingSecret);
	}

	/**
	 * 获取access_token
	 *
	 * CorpID
	 *            企业Id
	 * SECRET
	 *            管理组的凭证密钥，每个secret代表了对应用、通讯录、接口的不同权限；不同的管理组拥有不同的secret
	 * @return
	 */
	public static AccessToken getExpertToken() {
		return getAccessToken(ParamesAPI.expertSecret);
	}

	/**
	 * 获取access_token
	 *
	 * CorpID
	 *            企业Id
	 * SECRET
	 *            管理组的凭证密钥，每个secret代表了对应用、通讯录、接口的不同权限；不同的管理组拥有不同的secret
	 * @return
	 */
	public static AccessToken getWeekReportToken() {
		return getAccessToken(ParamesAPI.weekReportSecret);
	}

	/**
	 * 获取access_token
	 *
	 * CorpID
	 *            企业Id
	 * SECRET
	 *            管理组的凭证密钥，每个secret代表了对应用、通讯录、接口的不同权限；不同的管理组拥有不同的secret
	 * @return
	 */
	public static AccessToken getSaleTaskToken() {
		return getAccessToken(ParamesAPI.saleTaskSecret);
	}

	private static AccessToken getAccessToken(String secret){
		if(gson == null){
			gson = new Gson();
		}
		if(accessToken == null){
			accessToken = new AccessToken();
		}
		String requestUrl = access_token_url.replace("CorpID", ParamesAPI.corpId).replace(
				"SECRET", secret);
		String response = HttpUtils.sendGet(requestUrl, "utf-8");
		return gson.fromJson(response, AccessToken.class);
	}

	/**
	 * 获取access_token
	 *
	 * CorpID
	 *            企业Id
	 * SECRET
	 *            管理组的凭证密钥，每个secret代表了对应用、通讯录、接口的不同权限；不同的管理组拥有不同的secret
	 * @return
	 */
	public static AccessToken getProjectToken() {
		return getAccessToken(ParamesAPI.projectSecret);
	}



	public static String CODE_TO_USERINFO = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=";

	/**
	 * 根据code获取成员信息
	 * 
	 * 调用接口凭证
	 * @param code
	 *            通过员工授权获取到的code，每次员工授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期
	 * */
	public static String getUserID(String token,String code) {
		if(gson == null){
			gson = new Gson();
		}
		if(userInfo == null){
			userInfo = new UserInfo();
		}
		String code_url=CODE_TO_USERINFO+token+"&code="+code;		
		String response = HttpUtils.sendGet(code_url, "utf-8");
		return gson.fromJson(response, UserInfo.class).getUserId();
	}
	public static String SEND_TEXT_MSG = " https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";

	/**
	 * 根据code获取成员信息
	 *
	 * @param user
	 *
	 * */
	public static void createUser(User user) {
		//获取微信企业号AccessToken
		AccessToken accessToken = WeChatTokenUtil.getAddressBookAccessToken();
		String url = create_user_url.replace("ACCESS_TOKEN",accessToken.getAccess_token());
		WeChatUser weChatUser = new WeChatUser();
		weChatUser.setUserid(user.getLoginName());
		weChatUser.setName(user.getName());
		int[] i = {1};
		weChatUser.setDepartment(i);
		weChatUser.setMobile( user.getMobile());
		try {
			HttpUtils.sendPostUrl(url,new Gson().toJson(weChatUser),"utf-8");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 根据code获取成员信息
	 *
	 * @param
	 *
	 * */
	public static void deleteUser(User user) {
		//获取微信企业号AccessToken
		AccessToken accessToken = WeChatTokenUtil.getAddressBookAccessToken();
		String url = delete_user_url.replace("ACCESS_TOKEN",accessToken.getAccess_token()).replace("USERID",user.getLoginName());
		HttpUtils.sendGet(url,"utf-8");
	}

	/**
	 * 根据code获取成员信息
	 * 
	 * @param
	 *
	 * */
	public static void sendTextMsg(String touser,String toparty,String totag,int agentid,String content,int safe) {
		if(gson == null){
			gson = new Gson();
		}
		if(textMsg == null){
			textMsg = new TextMsg();
		}
		Text text = new Text();
		text.setContent(content);
		textMsg.setTouser(touser);
		textMsg.setToparty(toparty);
		textMsg.setTotag(totag);
		textMsg.setAgentid(agentid);
		textMsg.setMsgtype("text");
		textMsg.setText(text);
		textMsg.setSafe(safe);
		String token = null;
		switch (agentid){
			case 1000002:
				token = getBiddingAccessToken().getAccess_token();
				break;
			case 1000003:
				token = getExpertToken().getAccess_token();
				break;
			case 1000004:
				token = getWeekReportToken().getAccess_token();
				break;
			case 1000005:
				token = getSaleTaskToken().getAccess_token();
				break;
			case 1000006:
				token = getProjectToken().getAccess_token();
				break;
		}
		System.out.println("token="+token);
		String url=SEND_TEXT_MSG+token;	
		System.out.println(HttpUtils.sendPostUrl(url, gson.toJson(textMsg), "utf-8"));
	}
	
	/**
	 * 根据code获取成员信息
	 * 
	 *  access_token
	 *            调用接口凭证
	 * 
	 * */
	public static void sendMpnews(Articles articles, String touser,String toparty,String totag,int agentid,int safe) {
		if(gson == null){
			gson = new Gson();
		}
		if(mpnews == null){
			mpnews = new Mpnews();
		}
		mpnews.setTouser(touser);
		mpnews.setToparty(toparty);
		mpnews.setTotag(totag);
		mpnews.setAgentid(agentid);
		mpnews.setMsgtype("mpnews");
		mpnews.setArticles(articles);
		mpnews.setSafe(0);
		String token= getBiddingAccessToken().getAccess_token();
		String url=SEND_TEXT_MSG+token;	
		System.out.println(HttpUtils.sendPostUrl(url, gson.toJson(mpnews), "utf-8"));
	}
	
	
}
